<?php
/*
 +----------------------------------------------------------------------
 + Title        : ApiChannel 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2019/6/6 17:09
 + Last-time    : 2019/6/6 17:09+ 86187
 + Desc         : ApiChannel
 +----------------------------------------------------------------------
*/


namespace app\admin\service;


use app\common\lib\CacheConfig;
use app\common\lib\exception\ApiException;
use Ramsey\Uuid\Uuid;
use think\Db;
use think\facade\Cache;
use think\Model;

class ApiChannel extends Model
{
    private $txt       = 'Z1X2C3V4B5Np6oMi7uAy8tSr9eDw0qFlGkHjJhKgLfQdWsEaRmTnYbUvIcOxPz'; // 渠道ID与渠道KEY的数据池

    /**
     *
     * @param $data
     *
     * @return mixed
     * @throws ApiException
     * @author : Randy_chen
     * @Date   : 2019/8/8
     * @Time   : 12:01
     */
    public function setToken($data)
    {
        //验证
        $channel = db('api_channel')
            ->where('channel_id', $data['channel_id'])
            ->where('channel_key', $data['channel_key'])
            ->where('status', 1)
            ->find();
        if (!$channel) {
            throw new ApiException(10010);
        }
        $token = Uuid::uuid4()->toString();
        $key = CacheConfig::API_USER_TOKEN['key'] .$token;
        Cache::set($key, $channel, CacheConfig::API_TOKEN_USER['expire']);
        $data['expire_in'] = CacheConfig::API_USER_TOKEN['expire'];
        $data['access_token'] = $token;
        return $data;
    }

    //获取账户token
    public function getToken($token)
    {
        $key =  CacheConfig::API_USER_TOKEN['key'] .$token;
        return Cache::get($key);
    }

    /**
     * 生成长度为23的渠道ID
     * (唯一)
     * @return string
     */
    public function set_channel_id(){
        $str = '';
        for ($i = 0; $i < 23; $i++) {
            $str .= $this->txt[mt_rand(0,35)];
        }
        return $str;
    }

    /**
     * 生成长度为40的渠道KEY
     * @return string
     */
    public function set_channel_key(){
        $str = '';
        for ($i = 0; $i < 40; $i++) {
            $str .= $this->txt[mt_rand(0,35)];
        }
        return $str;
    }

    public function getChannel( $channel_id ,$update = false){
        $key = 'CHANNEL:'.$channel_id;
        $info = Cache::get($key);
        if($info ==false || $update ){
            $info = Db::name('api_channel')->where('channel_id' , $channel_id)->find();
            Cache::set($key , $info ,3600);
        }
        return $info;
    }
}